<template>
    <div class="clearfix">

        <!-- <div class="item" @click="selectFile" v-if="!onlyLook">
            <div class="item-img">
                <plus-outlined />
                <div style="margin-top: 8px">上传文件</div>

            </div>

        </div> -->
        <a-button type="primary" :icon="h(PlusOutlined)" @click="selectFile" v-if="!onlyLook">上传文件</a-button>
        <!-- {{ _fileList }} -->
        <a-space v-if="onlyLook">
            <a-tag v-for="(item, index) in _fileList"
                style=" cursor: pointer;" 
                @click="handleClick(item.url)" color="blue">{{ item.name}}</a-tag>
        </a-space>
        <div style="padding: 20px 0 0 0;" v-else>
            <div v-for="(item, index) in _fileList" class="file-item">
                <div class="file-con">
                    <div class="file-name" @click="handleClick(item.url)">{{ item.name }}</div>
                    <!-- <div class="file-speed">{{ item.speed }} == {{ item.percent }}</div> -->

                    <CloseOutlined  class="file-del" @click="remove(index)" />
                </div>
                <a-progress  :percent="item.percent" />
            </div>


        </div>

        <input ref="fileInput" @change="fileInputChange" type="file" :multiple="maxCount > 1" style="display: none;" />



        <a-modal :open="previewVisible" :title="previewTitle" :width="800" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>

    </div>
</template>
<script lang="ts" setup>
import { PlusOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { ref, h, watch, onMounted } from 'vue';
import { uploadFile } from '@/api/supportApi';
import { message } from 'ant-design-vue';
import { Form } from "ant-design-vue";
import axios from 'axios';

interface FileItem {
    id: string;
    name: string;
    percent: number;
    speed: number;
    url: string;
    source?: any;

}

const formItemContext = Form.useInjectFormItemContext();
const props = defineProps({
    maxCount: {
        type: Number,
        default: 1
    },

    onlyLook: {
        type: Boolean,
        default: false
    }
})

const value = defineModel<string>('value')
const list = defineModel<string[]>('list')

watch(value, (newVal, oldVal) => {
    watchValueHandle(newVal!)
})
watch(list, (newVal, oldVal) => {
    watchHandle(newVal!)
})

const watchValueHandle = (newVal: string) => {
    

    if (!newVal) {
        _fileList.value = []
        return
    }

    if (_fileList.value.length > 1) {
        return
    }



    _fileList.value = [{
        id: Math.random() + '',
        name: newVal.substring(newVal.indexOf('-') + 1),
        url: newVal,
        percent: 100,
        speed: 0
    }]
}

const watchHandle = (newVal: string[]) => {

    if (!newVal) {
        _fileList.value = []
        return
    }
    let arr = []
    for (let i of _fileList.value) {
        if (i.url) {
            arr.push(i.url)
        }
    }

    if (arr.join() == newVal!.join()) {
        return
    }


    _fileList.value = []
    if (newVal) {

        for (let item of newVal) {

            _fileList.value.push({
                id: Math.random() + '',
                name: item.substring(item.indexOf('-') + 1),
                url: item,
                percent: 100,
                speed: 0
            })


        }
    }
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const _fileList = ref<FileItem[]>([]);
let cancelCallBack


const fileInput = ref()
const selectFile = () => {
    if (_fileList.value.length >= props.maxCount) {
        message.error(`最多上传${props.maxCount}个`)
        return
    }
    fileInput.value.click()
}
const fileInputChange = async (e: any) => {

    let files = []
    for (let i of e.target.files) {
        i.id = Math.random() + ''
        files.push(i)
    }
    e.target.value = ''
    console.log(files)
    if (files.length + _fileList.value.length > props.maxCount) {
        message.error(`最多上传${props.maxCount}个`)
        return
    }
    for (let file of files) {
        _fileList.value.push({
            id: file.id,
            name: file.name,
            url: '',
            percent: 0,
            speed: 0
        })
    }
    console.log(JSON.stringify(_fileList.value))
    for (let file of files) {
        customRequest(file)
    }


}

const customRequest = async (file: File) => {

    const formData = new FormData();
    formData.append('file', file);
   

    function onProgress(event: any) {

        for (let f of _fileList.value) {
            if (f.id == file.id) {

                f.percent = Math.floor(event.progress * 100)

            }
        }
    }

    try {
        const CancelToken = axios.CancelToken;
        const source = CancelToken.source();
        for (let f of _fileList.value) {
            if (f.id == file.id) {
                f.source = source
            }
        }
        let res = await uploadFile(formData, onProgress, source)
        for (let f of _fileList.value) {
            if (f.id == file.id) {
                f.url = res
                emitValue()
            }
        }

    } catch (error) {
        for (let i = 0; i < _fileList.value.length; i++) {
            if (_fileList.value[i].id == file.id) {
                _fileList.value.splice(i, 1)
                emitValue()
            }
        }

    }




}

const remove = (index: number) => {

    if (_fileList.value[index].source) {
        console.log('取消上传')
        _fileList.value[index].source.cancel()
    }

    _fileList.value.splice(index, 1)

    emitValue()
}

const emitValue = () => {
    console.log('emitValue:', _fileList.value)
    let arr = []
    for (let i of _fileList.value) {
        if (i.url) {
            arr.push(i.url)
        }
    }


    console.log(arr)
    list.value = arr

    value.value = arr.join()
    formItemContext.onFieldChange()

}

const handleCancel = () => {
    previewVisible.value = false;
    previewTitle.value = '';
};
const handlePreview = (url: string) => {

    previewImage.value = url
    previewVisible.value = true;
    previewTitle.value = url.substring(url.lastIndexOf('/') + 1);
};

const getFileName = (url: string) => {
    return url.substring(url.indexOf('-') + 1)
}

const handleClick = (url: string) => {

    const link = document.createElement('a')
    link.href = location.origin + url
    link.download = getFileName(url)
    link.target = "_blank"
    link.click()
}

onMounted(() => {
    
    if(list.value){
        watchHandle(list.value)
    }
    
    if(value.value){
        watchValueHandle(value.value)
    }
    

})

</script>
<style scoped>
.item {
    display: inline-block;
    margin: 0 10px 10px 0;
    width: 102px;
    height: 102px;
    margin-inline-end: 8px;

    text-align: center;
    vertical-align: top;
    background-color: rgba(0, 0, 0, 0.02);
    border: 1px dashed #d9d9d9;
    border-radius: 8px;
    cursor: pointer;
    transition: border-color 0.3s;

    position: relative;
}

.item::before {
    content: '';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

.item-img {

    max-width: 100%;
    max-height: 100%;
    display: inline-block;
    vertical-align: middle;
}

.close-btn {
    position: absolute;
    color: red;
    right: 0;
    top: 0;
    cursor: pointer;
    font-size: 20px;
}

.file-item {}

.file-con {}

.file-name {
    display: inline-block;
    vertical-align: middle;
    width: 80%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
}

.file-speed {
    display: inline-block;
    vertical-align: middle;
}

.file-del {
    float: right;
    cursor: pointer;
}
</style>